import $service from '../../service';
const app = getApp()
let maxY = 0
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: {
    // 弹窗标题
    isShow: {
      type: Boolean,
      value: true
    },
    doctorData: {
      type: Object,
      value: ''
    },
    doctorId: {
      type: String,
      value: ''
    }
  },
  data: {
    QRImg: 'https://oss.yixianmedical.com/hospital/2021/6/30/1625047684654.jpg',
    headImage: '',
    icon: { //本地图片
      goodsIcon: '/static/images/my_doctor/icon_be_good_at.png',
      gouIcon: '/static/images/my_doctor/icon_authentication.png',
      backgroundImage: '/static/images/my_doctor/img_bg@2x.png'
    },
    doctorCard: "", //画布生成的图片src
    canvasHidden: false,
    canvas: {}, //画布对象
    ctx: {}
  },
  lifetimes: {
    ready() {
      this.getQRCode()
    },
  },
  methods: {
    // 获取验证码
    getQRCode() {
      let params = {
        "doctorId": this.properties.doctorId,
        "path": `pages/user_side/index/index_doctorlist/index_doctor_details/index_doctor_details?doctorId=${this.properties.doctorId}`,
        "width": '430',
      }
      app.http.getQRCode(params).then(res => {
        this.setData({
          QRImg: res.data.data
        })
        this.createCanvas()
      }).catch(err => {
        $service.showToast(err.msg)
      })
    },
    //隐藏弹框
    hideDialog() {
      this.setData({
        isShow: !this.data.isShow
      })
    },
    //展示弹框
    showDialog() {
      this.setData({
        isShow: !this.data.isShow
      })
    },
    /*
     * 内部私有方法建议以下划线开头
     * triggerEvent 用于触发事件
     */
    _cancelEvent() {
      //触发取消回调
      this.triggerEvent("cancelEvent")
    },
    // 长按保存二维码
    saveQR() {
      // 保存处方
      wx.showLoading({
        title: '图片保存中',
      })
      // wx.downloadFile({
      //   url: this.data.QRImg,
      // success: function (res) {
      //图片保存到本地
      wx.saveImageToPhotosAlbum({
        filePath: this.data.doctorCard,
        success: function (data) {
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
          })
        },
        fail: function (err) {
          if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
            wx.openSetting({
              success(settingdata) {
                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                  $service.showToast('请再次长按图片保存')
                } else {
                  $service.showToast('图库权限就无法正常使用')
                }
              },
              fail(e) {
                console.log(e)
              }
            })
          }
        },
        complete(res) {
          wx.hideLoading({})
        }
      })
      // }
      // })
    },

    //绘制canvas
    createCanvas() {
      //获取页面的canvas节点
      let ctxNode = this.createSelectorQuery()
      ctxNode.select("#qrCanvas")
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          console.log(res);
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          canvas.width = res[0].width * 2.5
          canvas.height = res[0].height * 2.5
          ctx.scale(2.5, 2.5)
          this.setData({
            canvas,
            ctx
          })
          ctx.fillStyle = '#fff'
          ctx.fillRect(0, 0, 300, 500)

          //写入文字
          ctx.font = 'bold 16px Arial';
          ctx.fillStyle = '#000';
          let nameWidth = ctx.measureText(this.data.doctorData.trueName).width
          ctx.fillText(this.data.doctorData.trueName, 70, 110);
          ctx.font = 'bold 14px serif';
          ctx.fillStyle = '#FF9211';
          ctx.fillText('已通过认证', nameWidth + 93, 110);
          ctx.font = '14px serif';
          ctx.fillStyle = '#353535';
          ctx.fillText(this.data.doctorData.doctorJobTitle, 85, 140);
          ctx.fillText('|', 145, 140);
          ctx.fillText(this.data.doctorData.departmentName, 160, 140);
          ctx.font = 'bold 14px serif';
          this.drawtext(ctx, '擅长:' + this.properties.doctorData.doctorSpecialty, 40, 178, 240)

          //认证图片icon画入
          this.addImage(this.data.icon.gouIcon).then((img) => {
            ctx.drawImage(img, nameWidth + 80, 100, 12.5, 12.5);
            //擅长图片icon画入
            this.addImage(this.data.icon.goodsIcon).then((img) => {
              ctx.drawImage(img, 15, 165, 12.5, 12.5)
              // 蓝色背景图片插入
              this.addImage(this.data.icon.backgroundImage).then((img) => {
                ctx.drawImage(img, 0, 350, 300, 150)
                ctx.fillStyle = '#fff';
                ctx.fillText(`hi，我是${this.data.doctorData.trueName}医生`, 80, 410);
                ctx.fillText('您可以扫二维码发起咨询。我会在最短时间', 10, 440);
                ctx.fillText('内回复并给出专业的诊疗方案', 50, 470);
                //医生二维码插入
                this.addImage(this.data.QRImg).then((img) => {
                  ctx.drawImage(img, 100, 288, 100, 100)
                  //医生头像画入
                  this.addImage(this.properties.doctorData.doctorHeadImg).then((img) => {
                    ctx.beginPath();
                    // //画裁剪区域，此处以圆为例
                    ctx.arc(148, 55, 31, 0, 2 * Math.PI);
                    // ctx.arc(50,50,25,0,2*Math.PI);
                    ctx.clip()
                    ctx.drawImage(img, 115.5, 24, 65, 65)
                    setTimeout(() => {
                      //将canvas画布转化为图片
                      wx.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                        width: this.data.windowWidth * 0.785,
                        height: this.data.windowHeight * 0.5,
                        destWidth: (this.data.canvasWidth * 750) / this.data.windowWidth,
                        destHeight: (((this.data.canvasWidth * 750) / this.data.windowWidth) * 785) / 500,
                        canvas: canvas,
                        success: (res) => {
                          console.log(res)
                          this.setData({
                            doctorCard: res.tempFilePath,
                            canvasHidden: true
                          })
                        },
                        fail: (err) => {
                          console.log(err);
                        }
                      })
                    }, 500)
                  })
                })
              })
            })
          })

          console.log(maxY); //医生擅长文字底部坐标
        })
    },
    //封装画图函数
    addImage(src) {
      return new Promise((resolve, reject) => {
        const img = this.data.canvas.createImage();
        img.src = src;
        img.onload = () => {
          resolve(img);
        };
        img.onerror = () => {
          reject();
          this.setData({
            canvasHidden: true
          })
        };
        if (img.complete) {
          resolve(img);
        }
      });
    },
    //绘制换行文字
    drawtext(ctx, t, x, y, w) {
      const chr = t.split('');
      let temp = '';
      const row = [];
      for (let a = 0; a < chr.length; a++) {
        if (
          ctx.measureText(temp).width < w &&
          ctx.measureText(temp + chr[a]).width <= w
        ) {
          temp += chr[a];
        } else {
          row.push(temp);
          temp = chr[a];
        }
      }
      row.push(temp);
      for (let b = 0; b < row.length; b++) {
        ctx.fillStyle = '#353535';
        ctx.fillText(row[b], x, y + b * 20); //每行字体y坐标间隔14
        maxY = y + b * 20
      }
    },
  }
})